package com.fau.wmbj.server.utils;

import cn.hutool.core.map.MapUtil;
import lombok.Setter;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Map;

/**
 * 原生sql查询工具类
 *
 * @author jiawei
 * @version 1.0
 */
@Setter
@Component
public class SqlUtils {

    @Resource
    @PersistenceContext
    private EntityManager entityManager;

    public SqlUtils(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public SqlUtils() {

    }

    public Object uniqueResult(String sql) {
        Session session = entityManager.unwrap(Session.class);
        return session.createQuery(sql).setMaxResults(1).uniqueResult();
    }

    public Object getList(String sql) {
        Session session = entityManager.unwrap(Session.class);
        return session.createQuery(sql).getResultList();
    }

    public Object getList(String sql, Map<Object, Object> param) {
        Session session = entityManager.unwrap(Session.class);
        Query query = session.createNativeQuery(sql);
        if (MapUtil.isNotEmpty(param)) {
            for (Object key : param.keySet()) {
                Object val = param.get(key);
                if (key instanceof String) {
                    query.setParameter(String.valueOf(key), val);
                } else if (key instanceof Integer) {
                    query.setParameter((int) key, val);
                }
            }
        }
        return query.getResultList();
    }

    public void update(String sql) {
        Session session = entityManager.unwrap(Session.class);
        session.createQuery(sql).executeUpdate();
    }

    public Object findOne(String sql, Class entity) {
        javax.persistence.Query query = entityManager.createNativeQuery(sql, entity).setMaxResults(1);
        return query.getSingleResult();
    }
}
